package cn.edu.nuc.article.util;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import org.bouncycastle.jcajce.io.CipherInputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;



public class SM4test {
    private static String key = "05d986b1141227cb20d46d0b5687c4f5";
    private static byte[] keyData = ByteUtils.fromHexString(key);
    static{
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null){
            //No such provider: BC
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    //生成 Cipher
    public static Cipher generateCipher(int mode,byte[] keyData) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(keyData, "SM4");
        cipher.init(mode, sm4Key);
        return cipher;
    }


    //加密文件
    public static CipherInputStream encryptFile(InputStream in){
        //加密文件
        try {
            Cipher cipher = generateCipher(Cipher.ENCRYPT_MODE,keyData);
            CipherInputStream cipherInputStream = new CipherInputStream(in, cipher);
            //FileUtil.writeFromStream(cipherInputStream, targetPath);
            //IoUtil.close(cipherInputStream);
            return cipherInputStream;
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 解密文件
     * @param targetPath 解密后的文件路径
     */
    public static void decryptFile(InputStream in, String targetPath) {
      //  FileInputStream in =null;
        ByteArrayInputStream byteArrayInputStream =null;
        OutputStream out = null;
        CipherOutputStream cipherOutputStream=null;
        CipherInputStream cipherIntputStream=null;

        try {
         //   in = new FileInputStream(sourcePath);
            byte[] bytes = IoUtil.readBytes(in);
            byteArrayInputStream = IoUtil.toStream(bytes);

            Cipher cipher = generateCipher(Cipher.DECRYPT_MODE,keyData);
            int c = 0;
            while ((c = in.read()) != -1) {// 读取输入流
                System.out.print((char) c);
            }
            if(in != null)
            {System.out.println("test");}
            int tem;
            while((tem=in.read())!=-1){System.out.print((char)tem);System.out.println("test");}
            System.out.println("testtest1");
            //FileUtil.writeFromStream(in, "D:\\bjsasc\\文件加解密\\enctesttest.txt");
            System.out.println("testtest2");
            out = new FileOutputStream(targetPath);
            //cipherOutputStream = new CipherOutputStream(out, cipher);
            cipherIntputStream = new CipherInputStream(byteArrayInputStream, cipher);
            FileUtil.writeFromStream(cipherIntputStream, targetPath);
            //IoUtil.copy(byteArrayInputStream, cipherOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }finally {
            IoUtil.close(cipherOutputStream);
            IoUtil.close(out);
            IoUtil.close(byteArrayInputStream);
            IoUtil.close(in);
        }
    }

    public static void main(String[] args) throws Exception {

        String sp = "D:\\bjsasc\\文件加解密\\test1.txt";//原始文件
        String dp = "D:\\bjsasc\\文件加解密\\enctest1.txt";//加密后文件
        String dp2 = "D:\\bjsasc\\文件加解密\\dectest1.txt";//解密后文件
        String dp3 = "D:\\bjsasc\\文件加解密\\enctesttest.txt";

        String key = "05d986b1141227cb20d46d0b5687c4f5";
        byte[] keyData = ByteUtils.fromHexString(key);
        //加密文件
        InputStream in = new FileInputStream(sp);
        //CipherInputStream cipherInputStream = null;

        InputStream encin;
        //encin = encryptFile(in);
        //FileUtil.writeFromStream(encin, dp);
        InputStream decin = new FileInputStream(dp3);
        //encryptFile(sp,dp);
        //解密文件
        //decryptFile(new FileInputStream(dp),dp2);
        decryptFile(decin,dp2);
    }
}
